"use strict";

const appRoot = require('app-root-path');
const PGMixin = require(appRoot + "/mixins/postgres.mixin");
const CacheCleanerMixin = require(appRoot + "/mixins/cache.cleaner.mixin");
const taskModel = require(appRoot + "/pgmodels/taskModel");
const moment = require('moment');
const {QueryTypes,Op,Transaction,literal} = require('sequelize');


/**
 * 定时任务表，所有定时任务都会被注册到此表
 * 然后分布式部署时，再到此表抢取任务执行
 */
module.exports = {
	name: "task",
	version:1,
	mixins: [PGMixin('task'),
		CacheCleanerMixin([
			"cache.clean.task",
		])],
	model:taskModel,


	settings:{
		auth:"ignore",
		excludeDBService:['list','create','get','update','remove'],//屏蔽所有框架自动生成的接口
	},

	/**
	 * Actions
	 */
	actions: {

		/**
		 * Register a new task
		 *
		 * @actions
		 * @param {Object} task - Task entity
		 *
		 * @returns {Object} Created entity
		 */
		createEntity: {
			rest: {
				method:'POST',
				path:"/",
			},
			params:{
				id:{ type:"number", optional:true, convert:true, integer:true, min:1,description:"项目空间"},
				namespace:{ type:"string", max:100 ,min:1, optional:false ,description:"项目空间"},
				projectName:{ type:"string", max:100 ,min:1, optional:false ,description:"项目名称"},
				taskName:{ type:"string", max:100 ,min:1, optional:false ,description:"任务名称"},
				description:{ type:"string", max:100 ,min:1, optional:true ,description:"任务描述（备注）"},
			},
			async handler(ctx) {
				let entity = ctx.params;
				const found = await this.adapter.findOne({
					where:{
						namespace:entity.namespace,
						projectName:entity.projectName,
						taskName:entity.taskName,
					}
				});
				if (!found){
					const doc = await this.adapter.insert(entity);
					const entityDb = await this.transformDocuments(ctx, {}, doc);
					await this.entityChanged("created", entityDb, ctx);
					return entityDb;
				}else{
					return found;
				}
			}
		},
	},

	/**
	 * Events
	 */
	events: {

	},

	/**
	 * Methods
	 */
	methods: {

	},

	/**
	 * Service created lifecycle event handler
	 */
	created() {

	},

	/**
	 * Service started lifecycle event handler
	 */
	async started() {

	},

	/**
	 * Service stopped lifecycle event handler
	 */
	async stopped() {

	}
};
